<template>
	<view class="content">
		<view class="top">
			<customHeader>
                <template v-slot:title>旭春灯饰生产信息管理生产看板</template>
            </customHeader>
		</view>
		<view class="center">
			<view style="border: 2rpx solid #ed1c24; margin-top: 20rpx; padding: 20rpx;">
				<view class="search_content">
					<view class="item_search">
						<text class="title">组别信息:</text>
						<!-- <input 
							class="input"
							v-model="form.zbinfo"
						/> -->
						<mySelectCheckbox 
							v-model="form.zbinfo" 
							style="flex: 1; width: 400rpx; height: 50rpx;"
							dataKey="name" 
							dataValue="id" 
							:localdata="zbinfoSelectList"  
							@change="changeZbinfo"></mySelectCheckbox>
					</view>
					<view class="item_search" >
						<text class="title">组长:</text>
						<input 
							class="input"
							v-model="form.teamLeader"
							disabled
						/>
						<!-- <mySelectCheckbox 
							v-model="form.teamLeader" 
							style="flex: 1; width: 400rpx; height: 50rpx;"
							dataKey="leader_name" 
							dataValue="leader_id" 
							:localdata="zteamLeaderSelectList"  
							@change="changeMember"></mySelectCheckbox> -->
					</view>

					<view class="item_search" style="">
						<text class="title">组员:</text>
						<input 
							class="input"
							v-model="form.members"
							disabled
						/>
						<!-- class="input" -->
						<!-- <mySelectCheckbox 
							v-model="form.members" 
							style="flex: 1; width: 400rpx; height: 50rpx;"
							multiple 
							dataKey="name" 
							dataValue="id" 
							:localdata="memberList"  
							@change="changeMember"></mySelectCheckbox> -->
					</view>
					<!-- <button @click="handleSearch" hover-class="btn" style="margin: 0; width: 320rpx; background: #008fe0; color: #fff; ">查询</button> -->
				</view>

				<view class="search_content" style="margin-top: 30rpx;" >
					<view class="item_search" style="margin-right: 12rpx;">
						<text class="title" style="margin-right: 12rpx;">当前订单数:</text>
						<input 
							class="input"
							text="number"
							v-model="form.dqdds"
							disabled
						/>
					</view>

					<view class="item_search" style="margin-right: 12rpx;">
						<text class="title" style="margin-right: 12rpx;">当前订单数量:</text>
						<input 
							class="input"
							text="number"
							v-model="form.dqddNum"
							disabled
						/>
					</view>
					<view class="item_search" style="margin-right: 12rpx;">
						<text class="title" style="margin-right: 12rpx;">当日完成数量:</text>
						<input 
							class="input"
							text="number"
							v-model="form.drwcNum"
							disabled
						/>
					</view>
					<view class="item_search" style="margin-right: 12rpx;">
						<text class="title" style="margin-right: 12rpx;">未完成数量:</text>
						<input 
							class="input"
							text="number"
							v-model="form.noNum"
							disabled
						/>
					</view>
					<view class="item_search" >
						<text class="title" style="margin-right: 12rpx;">本组累计产量:</text>
						<input 
							class="input"
							text="number"
							v-model="form.bzljcl"
							disabled
						/>
					</view>
				</view>
			</view>

			<view style="border: 2rpx solid #ffbf93; padding: 20rpx;">
				<t-table style="margin-top: 16rpx; background: #ffbf93;">
					<t-tr>
						<t-th style="flex:0 0 80upx;word-break: break-all;">序号</t-th>
						<t-th>订单编号</t-th>
						<t-th style="flex:0 0 220upx;">订单备注</t-th>
						<t-th>订单数量</t-th>
						<t-th>生产状态</t-th>
						<t-th>完成状态</t-th>
						<t-th>件数</t-th>
					</t-tr>
				</t-table>
				<scroll-view :scroll-top="0" scroll-y="true" class="table_content" @scrolltolower="handleScroll1">
					<t-table >
						<view  v-for="(item, index) in data1" :key="item.id" @click="handleItem(item, index)">
							<t-tr :style="{ backgroundColor: item.active ? '#81d3f8' : '' }">
								<t-td style="flex:0 0 80upx;word-break: break-all;">{{ index+1 }}</t-td>
								<t-td>{{ item.no }}</t-td>
								<t-td  style="flex:0 0 220upx;">{{ item.remark }}</t-td>
								<t-td>{{ item.total }}</t-td>
								<t-td>{{ normalMap[item.normal] }}</t-td>
								<t-td>{{ completedMap[item.completed] }}</t-td>
								<t-td>{{ item.pieces }}</t-td>
							</t-tr>
						</view>
					</t-table>
				</scroll-view>
			</view>

			<!--  -->

			<view style="border: 2rpx solid #9fa3e5; padding: 20rpx; margin-bottom: 20rpx;">

				<view class="center_1">
					<view class="center_item">
						<view class="item_title">订单详情: </view>
						<view>{{ ddNo }}</view>
					</view>
					<view class="center_item" style="margin-left: 60rpx;">
						<view class="item_title">订单数量: </view>
						<view>{{ddNum}}</view>
					</view>

					<view class="bao_btn">
						<button @click="handleEdit" hover-class="btn_hover"> {{ showEdit ? '完成' : '修改' }} </button>
						<button style="margin-left: 20rpx;" hover-class="btn_hover" @click=handlePrintPopupBox>打印</button>
					</view>

				</view>

				<t-table style="margin-top: 16rpx; background: #9fa3e5;">
					<t-tr>
						<t-th style="flex:0 0 220upx;">货号</t-th>
						<t-th >名称</t-th>
						<t-th style="flex:0 0 60upx;word-break: break-all;">件数</t-th>
						<t-th style="flex:0 0 120upx;word-break: break-all;">订单数量</t-th>
						<t-th style="flex:0 0 120upx;">完成数量</t-th>
						<t-th style="flex:0 0 220upx;">订单备注</t-th>
						<t-th style="flex:0 0 220upx;">生产备注</t-th>
						<t-th style="flex:0 0 120upx;word-break: break-all;">完成状态</t-th>
						<t-th style="flex:0 0 120upx;word-break: break-all;">员工</t-th>
					</t-tr>
				</t-table>

				<scroll-view :scroll-top="0" scroll-y="true" class="table_2_content">
					<t-table >
						<view  v-for="(item, index) in data2" :key="index">
							<t-tr>
								<t-td style="flex:0 0 220upx;">
									<view class="bao_td_left" >
										{{ item.materiel_no }}
									</view>
								</t-td>
								<t-td >
									<view class="bao_td_left" @click="handleBomPopup(item.materiel_id)" style="position: relative;" >
										<textarea 
											style="width: 100%; text-align: left; font-weight: 500; font-size: 26rpx;" 
											:auto-height="true"
											disabled
											v-model="item.materiel_name" />
										<view style="position: absolute; right: 0; top: 0; left: 0; bottom: 0;"></view>
									</view>
								</t-td>
								<t-td style="flex:0 0 60upx;word-break: break-all;">{{ item.pieces }}</t-td>
								<t-td style="flex:0 0 120upx;word-break: break-all;">{{ item.yquantity }}</t-td>
								<t-td style="flex:0 0 120upx;">
									<view style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;"@click="handleNumRecords(item)">
										{{ item.quantity }}
									</view>
								</t-td>
								<t-td  style="flex:0 0 220upx;">{{ item.sorderi_remark }}</t-td>
								<t-td  style="flex:0 0 220upx;">
									<textarea 
										:maxlength="-1" 
										style="max-height: 80rpx; width: 100%;" 
										v-model="item.remark" 
										:disabled="!showEdit"
									/>
								</t-td>
								<t-td style="flex:0 0 120upx;word-break: break-all;">
									<view @click="handleStatus(item, index)">
										{{ completedMap[item.completed]}}
									</view>
								</t-td>
								<t-td style="flex:0 0 120upx;word-break: break-all;">
									<view style="width: 100%; height: 100%; " @click="handleEmployee(item, index)">
										{{ item.staffsStr }}
									</view>
								</t-td>
							</t-tr>
						</view>
					</t-table>
				</scroll-view>

			</view>
		</view>

		<!--  -->

        <u-popup round="35" :show="showPopup" @close="showPopup = false" @open="handleOpen" mode="center">
            <view class="popup_content">
				<!--  -->
				<view  v-if="popuptitle == '员工信息'">
					<view  class="title">{{ popuptitle }}</view>
					<view class="popup_search">
						<input v-model="employeeName" />
						<button @click="queryName" hover-class="btn">查询</button>
					</view>
					<view class="selectAll_content">
						<checkbox-group @change="changeAll">
							<label>
								<checkbox value="selectAll" :checked="selectAll" /> 全选
							</label>
						</checkbox-group>

						<button @click="handleSearchGroupEmployees" hover-class="btn">本组员工</button>
					</view>
					<view class="checked_content">
						<scroll-view :scroll-top="0" scroll-y="true" class="table_3_content">
							<checkbox-group @change="checkboxChange">
								<label class="label_item" v-for="(item, index) in employeeList" :key="item.id">
									<view>
										<checkbox :value="item.no" :checked="item.checked" />
									</view>
									<view>{{ item.name }}</view>
								</label>
							</checkbox-group>
						</scroll-view>
					</view>

					<view class="popup_btn">
						<button  hover-class="btn" @click="confirmEmployee">确定</button>
						<button hover-class="btn1" @click="handleCancel">取消</button>
					</view>
				</view>
				<!--  -->
                <view v-else>
					<view  class="title">{{ popuptitle }}</view>
					<view class="checked_content">
						<scroll-view :scroll-top="0" scroll-y="true" class="table_3_content">
							<radio-group @change="radioChange">
								<label class="label_item" v-for="(item, index) in statusList" :key="index">
									<view>
										<radio  :value="item.labed" :checked="item.checked" />
									</view>
									<view style="font-size: 40rpx;">{{ item.labed }}</view>
								</label>
							</radio-group>
						</scroll-view>
					</view>
					<view class="popup_btn">
						<button hover-class="btn" @click="confirmStatus">确定</button>
						<button hover-class="btn1" @click="showPopup = false">取消</button>
					</view>
				</view>
				<!--  -->
				<view v-if="showToast" class="toast" >
					<view class="toast_msg" v-html="showToastStr"></view>
				</view>
            </view>
			<!--  -->
		</u-popup>

		<!-- 商品名称 BOM明细 -->
		<u-popup round="15" :show="showBomPopup" @close="showBomPopup = false" mode="center" :closeable="true">
			<view class="Bom_popup_comtent" >
				<view class="title">
					BOM明细
				</view>
				<view style="overflow: auto; flex: 1;">
					<view style="min-width: 1800rpx;">
						<t-table>
							<t-tr>
								<t-th style="flex:0 0 71upx;">序号</t-th>
								<t-th style="flex:0 0 250upx;word-break: break-all;">物料编号</t-th>
								<t-th >物料名称</t-th>
								<t-th style="flex:0 0 200upx;word-break: break-all;">单位</t-th>
								<t-th style="flex:0 0 220upx;">数量</t-th>
							</t-tr>
							<t-tr v-for="(item,index) in domList" :key="index">
								<t-th style="flex:0 0 71upx;">{{ index+1 }}</t-th>
								<t-th style="flex:0 0 250upx;word-break: break-all;">{{ item.materiel_no }}</t-th>
								<t-th >
									<view style="width: 100%; height: 100%;">
										<textarea 
											style="width: 100%; text-align: left; font-weight: 500;" 
											:auto-height="true"
											disabled
											v-model="item.materiel_name" />
									</view>
								</t-th>
								<t-th style="flex:0 0 200upx;word-break: break-all;">{{ item.materiel_unit_text }}</t-th>
								<t-th style="flex:0 0 220upx;">{{ item.quantity }}</t-th>
							</t-tr>
						</t-table>
					</view>
				</view>
				<!-- <view>底部啊</view> -->
			</view>
		</u-popup>

		<!-- 完成数量 弹出框 -->
		<u-popup round="15" :show="showNumPopup" @close="handleCancelNum" mode="center" :closeable="true">
			<view class="Bom_popup_comtent" style="width: 900rpx; max-height: 50vh; font-size: 39rpx;">
				<view class="title">
					完成数量
				</view>

				<view style="overflow: auto; flex: 1;">
					<view>
						<view style="display: flex; align-items: center; border-bottom: 1rpx solid #d1d1d1;">
							<view>完工数量:</view>
							<input style="flex: 1; font-size: 40rpx; margin-left: 50rpx;" v-model.number="numPupopMap.differenceNum" />
						</view>
						<view style="display: flex; align-items: center; border-bottom: 1rpx solid #d1d1d1; padding-top: 20rpx;" v-for="(item, index) in numPupopMap.reportDtl" :key="index">
							<view>完工数量：{{ item.quantity }} ,</view>
							<view style="margin-left: 50rpx;">完工时间：{{ item.endtime }}</view>
						</view>
					</view>
				</view>
				<view class="bom_bottom">
					<button hover-class="hover_btn" @click="handleNumPopup">确认</button>
					<button hover-class="hover_btn" @click="handleCancelNum">取消</button>
				</view>

				<view v-if="showToast" class="toast" >
					<view class="toast_msg" v-html="showToastStr"></view>
				</view>
			</view>
		</u-popup>


		<!-- 打印修改 数量 弹出框 开始 -->
		<uni-popup ref="printPopup" type="center">
			<view class="print_popup">
				<view style="font-size: 45rpx; margin: 10rpx 0; border-bottom: 1rpx solid #d1d1d1; ">打印份数</view>
				<view style="flex: 1;">
					<view class="dis_flex">
						<view>数量:</view>
						<input type="number" v-model.number="printSl" placeholder="请输入打印数量"/>
					</view>
				</view>
				<view class="dis_flex" style=" justify-content: space-around; padding: 10rpx 0; border-top: 1rpx solid #d1d1d1;">
					<button @click="printCancel">取消</button>
					<button @click="printSure">确认</button>
				</view>
			</view>
		</uni-popup>
		<!-- 打印修改 数量 弹出框 结束 -->

	</view>
</template>

<script>
import { mapState } from 'vuex'

import customHeader from '@/components/custom-header/custom-header.vue'
import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue'
import customDownSearch from '@/components/custom-downSearch/custom-downSearch.vue'
import customPagination from '@/components/custom-pagination/custom-pagination.vue'
import tTable from '@/components/t-table/t-table.vue'
import tTh from '@/components/t-table/t-th.vue'
import tTr from '@/components/t-table/t-tr.vue'
import tTd from '@/components/t-table/t-td.vue'
import mySelectCheckbox from '@/components/my-selectCheckbox/my-selectCheckbox.vue'
import tsc from "@/util/tsc.js";

import { getInforList, getInfoDetail, getEmployee, editEmployee, editWork, getWorkteams, getOrdeNum, editRemark, getDetail_materiel } from '@/api/modules/TVkanban.js'
	var timer_s = getNowFormatDate()
	var timer_e = getNowFormatDate()
	timer_s = timer_s.substring(0, 7) + "-01";

	function getNowFormatDate() {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		var currentdate = date.getFullYear() + seperator1 + month + seperator1 +
			strDate;
		return currentdate;

	}
	export default {
		components:{
			customHeader, 
			ruiDatePicker,
			customDownSearch,
			customPagination,
			tTable,
		    tTh,
		    tTr,
		    tTd,
			mySelectCheckbox,
		},
		data() {
			return {
				dates: timer_s,
				datee: timer_e,
				form: {
					zbinfo: [], // 组别信息 
					teamLeader:'', // 组长 
					members:'', // 组员 

					dqdds: '', // 当前订单数
					dqddNum: '', // 当前订单数量
					drwcNum: '', // 当日完成数量
					noNum: '', //未完成数量
					bzljcl: '', //本组累计产量
				},
				data1: [], // 生产信息列表
				data2: [], // 工单

				pageSize: 20, // 下单页数
				pageIndex: 1, // 当前页数
				totalCount: 1, // 应该有多少条数据

                showPopup: false, // 弹出框
				showBomPopup: false, // Bom 明细弹出框
				showNumPopup: false, // 完成数量弹出框
                popuptitle: '完成状态',
                statusList: [
                    { checked: false, labed: '已完成' },
                    { checked: false, labed: '未完成' },
                ], // 完成状态
				stateMap: {  // 订单状态
					'wmssoy_01': '待提交',
					'wmssoy_02': '待审核',
					'wmssoy_03': '待发货',
					'wmssoy_09': '已发货',
					'wmssoy_99': '已取消',
				},
				normalMap: { // 生产状态
					true: '正常',
					false: '异常',
				},
				completedMap: {
					true: '已完成',
					false: '未完成',
				},
				workOrderMap: { // 工单接口
					sorder_id: '',
					workteam_id: '', 
				},
				popupType: '', // 弹出框的状态类型
				data2_Map_item: {}, // 选中一条工单信息

				showToast: false, // 消息展示框
				showToastStr: '', // 提示框内容
				employeeList: [], // 员工数组
				selectEmployee: [], // 选中的员工数组

				zbinfoSelectList: [], // 组长 数组
				inputMemberList: [], // 获取组员数据
				zteamLeaderSelectList: [], // 组长 数组
				memberList: [], // 组员数组

				ddNo: '', // 订单编号
				ddNum: '', // 订单 数量
				workteam_id: '', // 组别 id
				employeeName: '', // 模糊查询员工名字
				selectAll: false, // 全选按钮
				popupSelectEmployList: [], // 弹出框选中的员工数组
				showEdit: false, // 是否是编辑状态

				delNoList: [], // 要删除的订单编号
				delNoTimer: null,  // 删除单号

				deletionTimers: [], // 存储删除定时器的应用
				domList: [], // BOM 明细
				numPupopMap: {}, // 弹出框记录
				onDutyNum: 0, // 暂存完成数量
				printSl: 1, // 打印数量

				// 蓝牙打印使用
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isLabelSend: false,
				isQuery: false,
				canvasWidth: 100,
				canvasHeight: 100,
				jpgWidth: 200,
				jpgHeight: 200,
				role: "",
				roleList: {},
				btnFlag: false,
				printArr: [],
				title: "",
				ids: "",
				ok_printer_sn: "",
				ydytitle: "",
				pz: 0,
				projectName: "",
				deviceId: '', // 设备 id 蓝牙使用
			}
		},
		async onLoad() {
			await this._getWorkteams() // 顶部 input 组员信息
			// await this._getInforList()  // 生产信息列表  1
			await this._getEmployee()
			// await this._getInfoDetail(); // 订单生产明细
			uni.removeStorageSync('BLEInformation');
		},
		onReady() { // 打印使用
			var list = [];
			var numList = [];
			var j = 0;

			for (var i = 20; i < 200; i += 10) {
				list[j] = i;
				j++;
			}

			for (var i = 1; i < 10; i++) {
				numList[i - 1] = i;
			}

			this.setData({
				buffSize: list,
				oneTimeData: list[0],
				printNum: numList,
				printerNum: numList[0],
			});
		},
		
		computed: {
			...mapState(['sideList', 'indexList']),
		},
		watch: {
			employeeList: {
				handler(newVal, oldVal) {
					if (newVal.length == 0) {
						this.selectAll = false
						return
					}
					if (newVal.every(i => i.checked)) {
						this.selectAll = true
					} else {
						this.selectAll = false
					}
				},
				immediate: true,
				deep: true
			},
		},
		methods: {

			handlePrintPopupBox() {
				this.$refs.printPopup.open('center')
			},
			printSure() {
				if (!this.printSl) {
					uni.showToast({
						title: '请输入数量',
						icon: 'none',
						duration: 1500
					})
					return
				}
				let lyName = uni.getStorageSync('BLEInformation')
				this.deviceId = lyName?.deviceId || ''
				if (!lyName) {
					uni.showToast({
						title: '请先连接蓝牙',
						icon: 'none'
					})
					uni.showModal({
						title: '提示',
						content: '请先连接蓝牙',
						success: function (res) {
							if (res.confirm) {
								uni.navigateTo({
										url: '../printSet/printSet'
								});
							}
						}
					});
					return
				}
				console.log('== 打印 ', this.printSl)

				const obj = {
					pm: `2节内置【DCH】115mm【大红】莲花灯【电商款/1#】+龙棒的额他好就个人我否个好就看好6`,
					no: '12220002',
					spec: '1200',
					sl: 2,
					date: '123456',
				}
				let arr = new Array(this.printSl).fill(null).map(() => ({...obj}));
				
				this.printCancel()
				this.printSingleItem(arr)
			},
			printCancel() {
				this.printSl = 1
				this.$refs.printPopup.close()
			},
			
			printSingleItem(arr) {  
				console.log('== arr 打印 ', arr)
				var command = tsc.jpPrinter.createNew();
				arr.forEach((item, index) => {
					command.setCls();
					command.setSize(60, 50);
					command.setGap(2);
					command.setCls();
					command.setBox(0, 10, 440, 380, 2); //绘制一个边框
					command.setBar(70, 10 , 2, 370) //  竖线 

					command.setBar(0, 200 , 440, 2) //  横线 
					command.setBar(0, 250 , 250, 2) //  横线 
					command.setBar(0, 295 , 250, 2) //  横线 
					command.setBar(0, 340 , 440, 2) //  横线 
					
					command.setBar(250, 200 , 2, 140) //  竖线 
					command.setText(4, 100, "TSS24.BF2", 0, 1, 1, `品名:`);
					if ( item.pm.length > 45 ) {
						command.setText(75, 50, "TSS24.BF2", 0, 1, 1, item.pm.substring(0, 15));
						command.setText(75, 50 + 35, "TSS24.BF2", 0, 1, 1, item.pm.substring(15, 30));
						command.setText(75, 50 + 35 * 2, "TSS24.BF2", 0, 1, 1, item.pm.substring(30, 45));
						command.setText(75, 50 + 35 * 3, "TSS24.BF2", 0, 1, 1, item.pm.substring(45));
					} else if (item.pm.length > 30) {
						command.setText(75, 75, "TSS24.BF2", 0, 1, 1, item.pm.substring(0, 15));
						command.setText(75, 75 + 35, "TSS24.BF2", 0, 1, 1, item.pm.substring(15, 30));
						command.setText(75, 75 + 35 * 2, "TSS24.BF2", 0, 1, 1, item.pm.substring(30, 45));
					}  else if (item.pm.length > 15) {
						command.setText(75, 85, "TSS24.BF2", 0, 1, 1, item.pm.substring(0, 15));
						command.setText(75, 85 + 35, "TSS24.BF2", 0, 1, 1, item.pm.substring(15, 30));
					}   else {
						command.setText(75, 100, "TSS24.BF2", 0, 1, 1, item.pm.substring(0, 15));
					}


					command.setText(4, 215, "TSS24.BF2", 0, 1, 1, `品号:`);
					command.setText(75, 215, "TSS24.BF2", 0, 1, 1, `${item.no}`);

					command.setText(4, 260, "TSS24.BF2", 0, 1, 1, `规格:`);
					command.setText(75, 260, "TSS24.BF2", 0, 1, 1, `${item.spec}`);

					command.setText(4, 305, "TSS24.BF2", 0, 1, 1, `数量:`);
					command.setText(75, 305, "TSS24.BF2", 0, 1, 1, `${item.sl}`);

					command.setText(4, 350, "TSS24.BF2", 0, 1, 1, `时间:`);
					command.setText(75, 350, "TSS24.BF2", 0, 1, 1, this.getCurrentTime());

					command.setQrcode(280, 210, "L", 6, 'A', item.no); // 绘制二维码
					command.setPagePrint(); //执行打印指令
					this.setData({
						isLabelSend: true,
					});
				})
				
				setTimeout(() => {
					this.prepareSend(command.getData());
				}, 500);
			},
			getCurrentTime() {
				// 获取当前时间
				const now = new Date();

				// 获取各个部分的时间信息
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				// 拼接成指定格式：YYYY-MM-DD HH:mm:ss
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			handleNumRecords(item) {
				this.numPupopMap = {}
				this.numPupopMap = item
				this.onDutyNum = item.differenceNum // 暂存完成数量
				this.showNumPopup = true
			},
			handleCancelNum() {
				this.showNumPopup = false
				this.numPupopMap.differenceNum = this.onDutyNum
			},
			async handleNumPopup() {
				let param = {
					no: this.numPupopMap.no,
					sorderi_id: this.numPupopMap.sorderi_id,
					cquantity: this.numPupopMap.differenceNum,
					id: this.numPupopMap.id,
				}
				let res = await editWork(JSON.stringify([param]))
				const  { data: { data, message, status	 } } = res || {}
				if ( status == 'success' ) {
					this.changeData('修改成功')
					setTimeout(async () => {
						this.showNumPopup = false;
						await this._getInfoDetail() // 先返回数据
					}, 1500)
				} else if (message === '未登陆系统，请先登陆') {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					this.changeData(message)
					await this._getInfoDetail() // 先返回数据
				}
				
			},
			async handleBomPopup(id) {
				this.domList = []
				const res = await getDetail_materiel(JSON.stringify({ id: id }))
				const { data, status, summary } = res.data || {}
				if (status == 'success') {
					this.showBomPopup = true
					const { bom } = data || {}
					const { bomis } = bom || {}
					this.domList = (bomis || [])
				} else {
					uni.showToast({
						title: summary,
						icon: 'none',
						duration: 2000,
					})
				}
			},
			async handleEdit() { // 修改删除备注
				if (this.showEdit) {
					let newData = this.data2.map(i => ({ no: i.no, remark: i.remark, id: i.id }))
					const res = await editRemark(JSON.stringify(newData))
					// console.log('== res', res)
					const { data: { status, message } } = res || {}
					if (status == 'success') {
						uni.showToast({
							title: "修改成功!",
							icon: 'none',
							duration: 2000,
						})
						this.showEdit = !this.showEdit
					} else if (message === '未登陆系统，请先登陆') {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					} else if (status == 'fail') {
						uni.showToast({
							title: message,
							icon: 'none',
							duration: 2000,
						})
					}

				} else {
					this.showEdit = !this.showEdit
				}
			},
			handleSearchGroupEmployees() {  // 查询本组员工数据
				this._getEmployee(this.employeeName, this.workteam_id)
			},
			mergeAndDeduplicateById(arr1, arr2) {
				let uniqueArr1 = arr1.filter(item1 => !arr2.some(item2 => item1.id ===item2.id))
				const mergedArray = [...arr2, ...uniqueArr1];  
				return mergedArray;  
			},
			changeAll() {
				this.selectAll = !this.selectAll
				if (this.selectAll) {
					this.employeeList = JSON.parse(JSON.stringify(this.employeeList)).map((i, j) => ({...i, checked: true}))
					this.popupSelectEmployList = JSON.parse(JSON.stringify(this.employeeList))
				} else if (!this.selectAll) {
					this.employeeList = JSON.parse(JSON.stringify(this.employeeList)).map((i, j) => ({...i, checked: false}))
					this.popupSelectEmployList = JSON.parse(JSON.stringify(this.employeeList))
				}
			},
			async queryName() {
				this._getEmployee(this.employeeName)
			},
			changeZbinfo(e) {
				this.workteam_id = e
				let selectItem = this.inputMemberList.filter(i => i.id == e)[0]
				this.form.teamLeader = selectItem?.leader_name
				this.form.members = selectItem?.members.map(i => i.name).join(',')
				this._getInforList() // 调用接口 第一个表格
				if (e) {
					this._getOrdeNum(e) // 获取 input 订单数量
				} else {
					this.form = {
						zbinfo: [], // 组别信息 
						teamLeader:'', // 组长 
						members:'', // 组员 
						dqdds: '', // 当前订单数
						dqddNum: '', // 当前订单数量
						drwcNum: '', // 当日完成数量
						noNum: '', //未完成数量
						bzljcl: '', //本组累计产量
					}
				}
			},
			changeMember(e) {
				console.log('=== 组员', e)
			},
			handleScroll1() {
				if ( this.pageIndex <= this.totalCount ) {
					this._getInforList(true)
				} else {
					uni.showToast({
						title: '没有更多数据了',
						duration: 2000,
						icon: 'none'
					});
				}
			},
			handleItem(item, index) {  // 切换 table 表格的
				this.data1 = JSON.parse(JSON.stringify(this.data1)).map((i, j) => ({...i, active: j == index ? true : false}))
				this.workOrderMap = { sorder_id: item.id , workteam_id: this.workteam_id , stopSchedule: 'false' }
				this.employeeList = JSON.parse(JSON.stringify(this.employeeList)).map(i => ({...i, checked: false}))
				this._getInfoDetail()
			},
			checkboxChange(e) {
				this.selectEmployee = e.detail.value
				// 点击选中员工的时候需要保持勾选
				this.popupSelectEmployList = this.employeeList.filter(i => this.selectEmployee.includes(i.no))
				let arr = JSON.parse(JSON.stringify(this.employeeList))
				arr.forEach(i => {
					if (e.detail.value.includes(i.no)) {
						i.checked = true
					} else {
						i.checked = false
					}
				})
				this.employeeList = arr
            },
            radioChange(e) {
				this.popupType = e.detail.value
            },
            handleEmployee(item, index) {
				this.popupSelectEmployList = item.staffs
                this.showPopup = true;
                this.popuptitle = '员工信息'
				let newList = this.employeeMatchId(item.staffs, this.employeeList)
				this.employeeList = JSON.parse(JSON.stringify(newList))
				this.data2_map_item = {
					id: item.id,
					no: item.no,
				}
            },
            handleStatus(item, index) {
                this.showPopup = true;
                this.popuptitle = '完成状态'

				let statu = this.completedMap[item.completed]
				this.statusList = JSON.parse(JSON.stringify(this.statusList)).map((i, j) => ({...i, checked: i.labed == statu ? true : false }))
				this.data2_Map_item = item

            },
			handleCancel() {
				this.showPopup = false
				this.employeeList = JSON.parse(JSON.stringify(this.employeeList)).map(i => ({...i, checked: false}))
				this.employeeName = ''
			},
			async confirmEmployee() {
				let list = this.employeeList.filter(i => this.selectEmployee.includes(i.no)).map(i => ({ id: i.id, no: i.no, name: i.name }))
				let param = [{
					...this.data2_map_item,
					staffs: list
				}]

				const res = await editEmployee(JSON.stringify(param))
				const  { data: { data, message, status	 } } = res || {}

				if ( status == 'success' ) {
					this.showPopup = false;
					this.changeData('修改成功')
					this._getInfoDetail()
				} else if (message === '未登陆系统，请先登陆') {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					this.changeData(message)
				}
				
			},

			async confirmStatus() { // 状态的弹出框
				let param = [{
					id: this.data2_Map_item.id,
					no:  this.data2_Map_item.no,
					cquantity: this.data2_Map_item.yquantity,
				}]

				const res = await editWork(JSON.stringify(param))

				const  { data: { data, message, status	 } } = res || {}
				if ( status == 'success' ) {
					this.showPopup = false;
					this.changeData('修改成功')
					await this._getInfoDetail() // 先返回数据
					// this._getInforList()
					await this.delComItem()  // 异步处理
				} else if (message === '未登陆系统，请先登陆') {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					this.changeData(message)
				}

			},
			delComItem() {
				// 判断子表的完成状态全部要都是 true
				if (this.data2.filter(i => i.completed)?.length == this.data2.length) {
					let newIndex = this.data1.findIndex(i => i.no == this.data1.filter(i => i.active)[0]?.no)
					
					// 修改主表的状态
					this.data1 = JSON.parse(JSON.stringify(this.data1)).map(i => ({
						...i,
						completed: i.active ? true : i.completed // 3.变成已完成
					}))

					this.deletionTimers[newIndex] = setTimeout(() => { // 3.删除数据 60 秒后
						this.data1 = JSON.parse(JSON.stringify(this.data1)).filter(i => i.no !== this.deletionTimers[newIndex].split('bao_^_*')[1])

						// this._getInforList()
					}, (1000 * 60)) + 'bao_^_*' + this.data1.filter(i => i.active)[0]?.no
				}
			},
            handleOpen() {
                this.showPopup = true
            },
			handleSearch() {
				const {  zbinfo, teamLeader, members, dqdds, dqddNum, drwcNum, noNum, bzljcl } = this.form
			
				let param = {
					startdate: this.dates,
					enddate: this.datee,

					zbinfo: zbinfo, // 组别信息 
					teamLeader: teamLeader, // 组长 
					members: members, // 组员 

					dqdds: dqdds, // 当前订单数
					dqddNum: dqddNum, // 当前订单数量
					drwcNum: drwcNum, // 当日完成数量
					noNum: noNum, //未完成数量
					bzljcl: bzljcl, //本组累计产量
				}
			},
		   
			async _getInforList( type ) { //  // 生产信息列表  1
				let param = {
					paging: {
						pageIndex: this.pageIndex,
						pageSize: 20,
					},
					query: {
						workteam_id: this.workteam_id,
						completed: false,
						// workteam_id: 4,
						// startdate: this.dates,
						// enddate: this.datee,
					}
				}
				const res = await getInforList(JSON.stringify(param))
				// console.log('== res 订单列表', res)

				const { data: { data, message, status	 } } = res || {}

				if (status == 'success') {
					this.data1 = data.sorders.map((i, j) => ({...i, state: this.stateMap[i.state], active: j == 0 ? true : false}))

					if (type) {
						let newData = this.data1
						this.data1 = newData.concat(  data.sorders.map((i, j) => ({...i, state: this.stateMap[i.state], active: false})) )
					} else {
						this.data1 = data.sorders.map((i, j) => ({...i, state: this.stateMap[i.state], active: j == 0 ? true : false}))
					}

					this.workOrderMap = { sorder_id: (data.sorders.length ? data.sorders[0]?.id : '') , workteam_id: this.workteam_id, stopSchedule: 'false'  }
					this._getInfoDetail() // 第二张表格

					// 上划加载更多
					let totalPage = Math.ceil(data.paging.total / 20)
					this.totalCount = totalPage
					// if (totalPage > this.pageIndex) {
					// 	this.pageIndex++
					// }

					if (data.paging.pageIndex == this.pageIndex) {
						this.pageIndex++
					}

				} else if (message === '未登陆系统，请先登陆') {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				} 
			},

			async _getEmployee( str = '', id = '' ) {
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 20,
					},
					query: {
						// workteam_id: this.workteam_id,
						workteam_id: id, // 指定班组id
						valid: true,
						search: str,
					}
				}
				const res = await getEmployee(JSON.stringify(param))

				const { data: { data, message, status	 } } = res || {}

				if (status == 'success') {

					if (id) { // 查询本组员工
						let arr2 = this.mergeAndDeduplicateById(this.employeeList, data.staffs.map(i => ({...i, checked: true})))
						this.employeeList = JSON.parse(JSON.stringify(arr2))
						return
					}

					if (str.length) {
						if (!this.employeeList.filter(i => data.staffs.some(j => i.id == j.id)).length) {
							this.employeeList.unshift(...data.staffs.map(i => ({...i, checked: false})))
						}
					} else {
						if (this.popupSelectEmployList.length) {
							let newList = this.mergeAndDeduplicateById(this.popupSelectEmployList, this.employeeList)
							this.employeeList = JSON.parse(JSON.stringify(newList))
						} else {
							this.employeeList = data.staffs.map(i => ({...i, checked: false}))
						}
					}

					if ( !data.staffs.length ) {
						this.changeData('查找不到该员工!')
					}
				} else if (message === '未登陆系统，请先登陆') {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				}


			},
			async _getInfoDetail() { // 工单明细
				const res = await getInfoDetail(JSON.stringify(this.workOrderMap))
				const  { data: { data, message, status	 } } = res || {}
				if ( status == 'success' ) {
					this.data2 = data.worders.map(i => ({
						...i, state: this.stateMap[i.state], 
						staffsStr:  i.staffs.map(i => i.name).join('、'),
						differenceNum: (Number(i.yquantity) || 0) - Number(i.quantity) || 0
					}))
					this.ddNo = data.no
					this.ddNum = data.total

				} else if (message === '未登陆系统，请先登陆') {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				} 
			},
			async _getWorkteams() {  // 获取班组信息
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: -1,
					},
					query: {
						valid: true,
						search: ''
					}

				}
				const res = await getWorkteams(JSON.stringify(param))

				const  { data: { data, message, status	 } } = res || {}

				if ( status == 'success' ) {
					this.zbinfoSelectList = data.workteams.map(i => ({ name: i.name, id: i.id }))
					this.zteamLeaderSelectList = data.workteams.map(i => ({ leader_name: i.leader_name, leader_id: i.leader_id }))

					this.memberList = (data.workteams[0]?.members || [])
					this.inputMemberList = data.workteams
					if (this.zbinfoSelectList.length) {
						this.workteam_id = this.zbinfoSelectList[0].id
						this.form.zbinfo = this.zbinfoSelectList[0].id
						this.form.teamLeader = data.workteams[0].leader_name
						this.form.members = data.workteams[0].members.map(i => i.name).join(',')
					}
					this._getInforList() // 调用接口 第一个表格

					this._getOrdeNum() // 获取用户信息接口

				} else if (message === '未登陆系统，请先登陆') {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				}
			},
			async _getOrdeNum(id) {
				const param = {
					workteam_id: this.workteam_id,
				}
				const res = await getOrdeNum(JSON.stringify(param))
				const  { data: { data, message, status	 } } = res || {}
				if ( status == 'success' ) {
					this.form = {
						...this.form,
						dqdds: data.sorder_num,
						dqddNum: data.sorder_qty,
						drwcNum: data.comp_qty,
						noNum: data.unf_qty,
						bzljcl: data.total,
					}
				} else if (message === '未登陆系统，请先登陆') {
				    uni.navigateTo({
						url: '/pages/login/login'
					});
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				}
			},
			employeeMatchId(arr1, arr2) {
				let newData = JSON.parse(JSON.stringify(arr2))
				arr1.forEach((i, index) => {  
					const matchingStaff2 = newData.find(j => j.id === i.id);  
					if (matchingStaff2) {  
						matchingStaff2.checked = true;  
					}  else {
						matchingStaff2.checked = false;  
					}
				});  
				return newData;  
			},
			changeData(param) {  // img 信息弹出框
				this.showToast = true;
				this.showToastStr = param
				this.timer = setTimeout(() => {
					this.showToast = false;
					clearTimeout(this.timer)
				}, 3000)
			},
			// 蓝牙方法
			prepareSend: function (buff) {
				//准备发送，根据每次发送字节数来处理分包数量
				//console.log(buff)
				var that = this;
				var time = that.oneTimeData;
				var looptime = parseInt(buff.length / time);
				var lastData = parseInt(buff.length % time); //console.log(looptime + "---" + lastData)

				that.setData({
					looptime: looptime + 1,
					lastData: lastData,
					currentTime: 1,
				});
				that.Send(buff);
			},
			Send: function (buff) {
				//分包发送
				var that = this;
				var currentTime = that.currentTime;
				var loopTime = that.looptime;
				var lastData = that.lastData;
				var onTimeData = that.oneTimeData;
				var printNum = that.printerNum;
				var currentPrint = that.currentPrint;
				var buf;
				var dataView;

				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData);
					dataView = new DataView(buf);

					for (var i = 0; i < onTimeData; ++i) {
					dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
					}
				} else {
					buf = new ArrayBuffer(lastData);
					dataView = new DataView(buf);

					for (var i = 0; i < lastData; ++i) {
					dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
					}
				} //console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)

				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: "49535343-FE7D-4AE5-8FA9-9FAFD205E455",
					characteristicId: "49535343-8841-43F4-A8D4-ECBE34729BB3",
					value: buf,
					success: function (res) {
					if (currentPrint == printNum) {
						uni.showToast({
						title: "已打印第" + currentPrint + "张成功",
						});
					} //console.log(res)
					},
					fail: function (e) {
						uni.showToast({
							title: "打印第" + currentPrint + "张失败",
							icon: "none",
						});
					},
					complete: function () {
					currentTime++;

					if (currentTime <= loopTime) {
						that.setData({
						currentTime: currentTime,
						});
						that.Send(buff);
					} else {
						// wx.showToast({
						//   title: '已打印第' + currentPrint + '张',
						// })`
						if (currentPrint == printNum) {
						that.setData({
							looptime: 0,
							lastData: 0,
							currentTime: 1,
							isLabelSend: false,
							currentPrint: 1,
						});
						} else {
						currentPrint++;
						that.setData({
							currentPrint: currentPrint,
							currentTime: 1,
						});
						that.Send(buff);
						}
					}
					},
				});
			},
			// 蓝牙方法
		}
	}
</script>

<style lang="less" scoped>
.content {
	.top {
		position: fixed;
		width: 100%;
		z-index: 12;
	}

	.bao_td_left {
		width: 100%;
		height: 100%;
		text-align: left;
	}

	.center {
		padding: 0 40rpx;
		padding-top: 158rpx;

		/* 隐藏滚动条 
		::-webkit-scrollbar {
			display: none;
		}
		-ms-overflow-style: none;
		scrollbar-width: none;
		*/

		.search_content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			.item_search {
				display: flex;
				align-items: center;
				height: 60rpx;

				.title {
					font-size: 40rpx;
					font-weight: 700;
					margin-right: 30rpx;
					white-space: nowrap;
				}
                .input {
                    flex: 1; 
                    height: 30rpx; 
                    border: 1rpx solid #ccc; 
                    font-size: 30rpx;
                    padding: 12rpx 8rpx; 
                }
			}
		}

		.search_btn {
			display: flex;
			justify-content: space-between;
			margin: 30rpx;

			button {
				width: 360rpx;
				color: #fff;
				margin: 0;
				font-size: 50rpx;
			}

			button:nth-child(1) {
				background: red;
			}
			button:nth-child(2) {
				background: #f59a23;
			}
		}
		
		.table_content {
			// height: calc(100vh - 1400rpx);
			min-height: 300rpx;
			max-height: 400rpx;
			// height: calc(100vh - 1588rpx);
			width: 100%;
			// background: red;
		}

		.bottom_contetn {
			margin-top: 40rpx;
			font-size: 34rpx;

			.none {
				border: none;
			}
		}

        .center_1 {
            display: flex;
            padding: 20rpx 0;

            .center_item {
                display: flex;
                align-items: center;
                .item_title {
                    font-size: 40rpx;
                    font-weight: 700;
                    margin-right: 20rpx;
                }
            }

			.bao_btn {
				display: flex;
				align-items: center;
				margin-left: 60rpx;

				button {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 160rpx;
					height: 60rpx;
					background: #18aff2;
					color: #fff;
					border-radius: 10rpx;
					font-size: 30rpx;
				}

				.btn_hover {
					background: #1392c9 !important;
				}
			}
        }
        .table_2_content {
            width: 100%;
            // height: calc(100vh - 1240rpx);
            min-height: 300rpx;
            max-height: 400rpx;
			// background: skyblue;
        }
	}


    .popup_content {
        width: 800rpx;
        // height: 900rpx;
        background: #fff;
        padding: 60rpx;
		border-radius: 55rpx;

		.toast {
			position: absolute;
			top: 140rpx;
			left: 400rpx;
			
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 40rpx;
			border-radius: 15rpx;
			background: #575757;
			color: #fff;
			font-size: 30rpx;

			.toast_msg {
				max-height: 600rpx;
				max-width: 1000rpx;
				overflow: auto;
			}
		}

        .title {
            font-size: 56rpx;
            font-weight: 700;
        }

        .popup_search {
            display: flex;
            align-items: center;
            margin-top: 20rpx;

            input {
                border: 1rpx solid #ccc;
                padding: 12rpx 8rpx;
                margin-right: 100rpx;
            }
            button {
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0px;
                height: 80rpx;
                color: #fff;
                background: #008fe0;
            }
        }

		.selectAll_content {
			display: flex;
            align-items: center;
            margin-top: 20rpx;

			button {
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0px;
                height: 80rpx;
                color: #fff;
                background: #008fe0;
				margin-left: 320rpx;
            }
		}


        .checked_content {
            border: 1rpx solid #ccc;
            padding: 10rpx;
            margin-top: 20rpx;

            .table_3_content {
                height: 500rpx;

                .label_item {
                    display: flex;
                    align-items: center;
                    margin-bottom: 10rpx;
                }
            }
        }

        .popup_btn {
            display: flex;
            justify-content: flex-end;
            margin-top: 40rpx;
            button {
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0px;
                height: 66rpx;
                width: 300rpx;
            }
            button:nth-child(1) {
                color: #fff;
                background: #008fe0;
                margin-right: 20rpx;
            }
            button:nth-child(2) {
                color: #008fe0;
                border: 1rpx solid #008fe0;
                background: #fff;
            }
        }
    }

	.Bom_popup_comtent {
		width: 80vw;
		max-height: 80vh;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		position: relative;

		.title {
			font-size: 40rpx;
			font-weight: bold;
			text-align: center;
		}

		.bom_bottom {
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding-top: 20rpx;

			button {
				margin: 0;
				width: 240rpx;
				background: #18aff2;
				color: #fff;
			}

			.hover_btn {
				background: #1497cf;
			}
		}

		.toast {
			position: absolute;
			top: 50%;
			left: 50%;
			
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 40rpx;
			border-radius: 15rpx;
			background: #575757;
			color: #fff;
			font-size: 30rpx;

			.toast_msg {
				max-height: 600rpx;
				max-width: 1000rpx;
				overflow: auto;
			}
		}
	}

    .btn {
        color: #d6d5d5 !important;
        background: #006faf !important;
    }
    .btn1 {
        color: #0374b6 !important;
        background: #d3d3d3 !important;
    }

	// 打印弹出框样式
	.print_popup {
		width: 800rpx; 
		height: 300rpx; 
		background: #fff; 
		border-radius: 20rpx; 
		padding: 10rpx; 
		display: flex; 
		flex-direction: column;
		font-size: 40rpx;

		.dis_flex {
			display: flex;
			align-items: center;
			input {
				flex: 1;
			}
		}
		button {
			margin: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 160rpx;
			height: 60rpx;
			background: #18aff2;
			color: #fff;
			border-radius: 10rpx;
			font-size: 30rpx;
		}
	}
}
</style>
